﻿using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using log4net;
namespace Vepa.Server.Networking
{ 
    
    class TCPServer
    {
        #region Fields
        /// <summary>
        /// Port of the server to listen on. Can't be changed while the server is running (call Stop() first).
        /// </summary>
        public int serverListenPort = 7879;

        private TcpListener listener = new TcpListener(IPAddress.Any,7879);
        private List<ServerThread> serverThreads = new List<ServerThread>();
        private Thread mainThread;
        private static readonly ILog log = LogManager.GetLogger(typeof(TCPServer));
        #endregion

        #region Constructor
        public TCPServer()
        {          
        }
        #endregion

        #region Methods
        /// <summary>
        /// Starts listening.
        /// </summary>
        public void Start()
        {
            log.Info("Starting Listern on Port " + serverListenPort);
            listener.Start();
            mainThread = new Thread(new ThreadStart(listen));
            mainThread.Start();
        }
        /// <summary>
        /// Stops listening and kills all open connections.
        /// </summary>
        public void Stop()
        {
            log.Info("Killing all TCP connections");
            mainThread.Abort();
           
            foreach (ServerThread st in serverThreads)
            {
                st.stop = true;
                while (st.running)                
                    Thread.Sleep(500);                
            }
        }

        private void listen()
        {
            log.Info("Listining...");
            while (true)
            {
                TcpClient c = listener.AcceptTcpClient();
                serverThreads.Add(new ServerThread(c));
            }
        }
        #endregion
    }
}
